package demo_0712;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class T8_0328 {
    //非递归实现二叉树的前序遍历
    //前序遍历：根左右
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                list.add(root.val);
                root = root.left;
            }
            TreeNode prev = stack.pop();
            root = prev.right;
        }
        return list;
    }
}
